// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { 
    title, 
    description, 
    backgroundImage, 
    options, 
    endTime, 
    _activityId 
  } = event

  // 参数验证
  if (!title) {
    return {
      success: false,
      message: '投票标题不能为空'
    }
  }

  if (!options || !Array.isArray(options) || options.length < 2) {
    return {
      success: false,
      message: '至少需要2个投票选项'
    }
  }

  // 验证选项格式
  for (let i = 0; i < options.length; i++) {
    const option = options[i]
    if (!option.name) {
      return {
        success: false,
        message: `第${i + 1}个选项名称不能为空`
      }
    }
  }

  try {
    // 处理选项数据，确保每个选项都有必要的字段
    const processedOptions = options.map((option, index) => ({
      id: index,
      name: option.name,
      avatarUrl: option.avatarUrl || '',
      votes: 0
    }))

    // 创建投票活动
    const addResult = await db.collection('vote_activity').add({
      data: {
        title: title,
        description: description || '',
        backgroundImage: backgroundImage || '',
        options: processedOptions,
        endTime: endTime ? new Date(endTime) : null,
        _activityId: _activityId || null,
        totalVotes: 0,
        _createTime: new Date(),
        _updateTime: new Date(),
        creatorOpenid: wxContext.OPENID
      }
    })

    if (!addResult._id) {
      return {
        success: false,
        message: '创建投票活动失败'
      }
    }

    // 如果关联了活动，更新活动表中的voteId
    if (_activityId) {
      try {
        await db.collection('activities').doc(_activityId).update({
          data: {
            voteId: addResult._id,
            _updateTime: new Date()
          }
        })
      } catch (error) {
        console.error('更新活动voteId失败:', error)
        // 不影响投票创建，只记录错误
      }
    }

    return {
      success: true,
      message: '创建投票活动成功',
      data: {
        voteId: addResult._id,
        title: title,
        optionsCount: processedOptions.length
      }
    }

  } catch (error) {
    console.error('创建投票活动失败:', error)
    return {
      success: false,
      message: '创建投票活动失败',
      error: error.message
    }
  }
}